package com.dean.ui;

import com.dean.constants.DeanUiConstants;
import com.dean.dao.DeanToolDao;
import com.dean.entity.SysMenu;
import com.dean.ui.panel.DeanPanel;
import com.dean.ui.utils.UiUtils;
import com.dean.utils.FileUtils;
import com.formdev.flatlaf.FlatIntelliJLaf;
import com.formdev.flatlaf.extras.FlatSVGIcon;
import com.formdev.flatlaf.extras.components.FlatSplitPane;
import com.formdev.flatlaf.extras.components.FlatTabbedPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @ClassName DeanMainUi
 * @Description dean 小工具主页面
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class DeanMainUI extends Frame{
	private static final Logger logger = LoggerFactory.getLogger(DeanMainUI.class);
	// frame
	private static JFrame frame;
	/**
	 * 将页面缓存
	 */
	private Map<String,JPanel> menuPanels = new HashMap<String, JPanel>();

	// 页面采取左右布局
	private FlatSplitPane splitPanel = new FlatSplitPane();

	private JPanel menuPanel;

	// private TabbedPane contentPanel;
	// private FlatTabbedPane contentPanel;
	// private JTabbedPane contentPanel;
	private FlatTabbedPane contentPanel;



	private JPanel deanPanel;

	private JList<String> menuList;

	private static Dimension menuItemSize;

	public static void main(String[] args) throws IOException {
		DeanMainUI deanMainUI = new DeanMainUI();
	}


	public DeanMainUI()  {
		// 初始化配置 应用目录以及配置文件
		initConfigPath();
		// 初始化页面
		initialize();
	}

	/**
	 * 主页面初始化
	 * @throws IOException
	 */
	private void initialize()  {
		// 开启一个窗口
		frame = new JFrame("稀世之宝,温润而泽");
		// 开启UI美化
		try {
			// 设置主题
			 UIManager.setLookAndFeel(new FlatIntelliJLaf());
			// UIManager.setLookAndFeel(new FlatDarculaLaf());
			// UIManager.setLookAndFeel(new BeautyEyeLookAndFeelCross());
			// BeautyEyeLNFHelper.launchBeautyEyeLNF();
			// 给所有页面都使用该主题
			 SwingUtilities.updateComponentTreeUI(frame);
			// 最合适的方式显示
			 frame.pack();

		} catch (Exception e1) {
			logger.error("设置主题失败:{}",e1.getMessage(),e1);
		}
		// 计算屏幕大小
		UiUtils.getScreenSize();
		// 全局字体设置
		initGlobalFontSetting(new Font("微软雅黑",Font.PLAIN,12));
		// 页面最大化
		frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		// 屏幕中央
		frame.setLocationRelativeTo(null);

		//設置分割綫方向
		splitPanel.setOrientation(FlatSplitPane.HORIZONTAL_SPLIT);
		splitPanel.setResizeWeight(0.072);
		// splitPanel.setOneTouchExpandable(true);

		menuPanel = new JPanel();
		JScrollPane menuScrollPanel = new JScrollPane();
		menuList = new JList<String>();
		JPopupMenu popupMenu = new JPopupMenu();
		List<SysMenu> menus = DeanToolDao.getInstance().queryMenu();
		menuList.setModel(new AbstractListModel<String>() {
			@Override
			public int getSize() {
				return menus.size();
			}

			@Override
			public String getElementAt(int index) {
				return menus.get(index).getMenuName();
			}
		});
		menuList.setComponentPopupMenu(popupMenu);
		menuScrollPanel.setViewportView(menuList);
		menuScrollPanel.setPreferredSize(new Dimension(UiUtils.menuItemWidth,UiUtils.noBorderHeight - UiUtils.elePadding));
		menuScrollPanel.setMaximumSize(new Dimension(UiUtils.menuItemWidth,UiUtils.noBorderHeight - UiUtils.elePadding));
		menuPanel.add(menuScrollPanel,"cell 1 0");
		menuList.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				String  menuName = menuList.getSelectedValue();
				logger.debug("点击菜单:{}",menuList.getSelectedValue());
				int index = menuList.getSelectedIndex();
				SysMenu menu = menus.get(index);
				int tabIndex = -1;
				for (int i = 0; i < contentPanel.getTabCount(); i++) {
					// 如果存在则直接启用tab 否则 重新开启一个新的tab
					String tabName = contentPanel.getTitleAt(i);
					logger.debug("tab name is :{}",tabName);
					if(menuName.equals(tabName)){
						tabIndex = i;
						break;
					}
				}
				// 没有存在的tab 则重新开启一个tab
				if(tabIndex == -1){
					DeanPanel deanPanel = null;
					try {
						deanPanel = (DeanPanel) Class.forName(menu.getMenuClass()).newInstance();
					} catch (InstantiationException instantiationException) {
						logger.error(instantiationException.getMessage(),instantiationException);
					} catch (IllegalAccessException illegalAccessException) {
						logger.error(illegalAccessException.getMessage(),illegalAccessException);
					} catch (ClassNotFoundException classNotFoundException) {
						logger.error(classNotFoundException.getMessage(),classNotFoundException);
					}
					// contentPanel.addTab(menuName,new FlatTabbedPaneCloseIcon(),deanPanel.showView());
					contentPanel.addTab(menuName,null,deanPanel.showView());
					tabIndex = contentPanel.getTabCount()-1;
					// contentPanel.setTabClosable(tabIndex,true);

				}
				contentPanel.setSelectedIndex(tabIndex);
				// logger.debug("tab height{}",contentPanel.getTabHeight());
			}
		});
		splitPanel.setLeftComponent(menuPanel);

		contentPanel = new FlatTabbedPane();

		deanPanel = new JPanel();
		contentPanel.addTab("首页",new FlatSVGIcon("com/formdev/flatlaf/demo/icons/search.svg", 16, 16),deanPanel);
		splitPanel.setRightComponent(contentPanel);

		contentPanel.setTabClosable(0,false);
		contentPanel.setTabsClosable(true);
		contentPanel.setTabCloseCallback((tabPane,tabIdx)->{
			tabPane.remove(tabIdx);
		});
		frame.getContentPane().add(splitPanel,BorderLayout.CENTER);

		//使窗体可见
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	/**
	 * 初始目录建立 resource文件copy
	 */
	private void initConfigPath(){
		File file = new File(DeanUiConstants.INIT_PATH);
		if(!file.exists()){
			file.mkdirs();
		}
		// 初始化各种配置文件
		FileUtils.copyResourceFile();
	}

	/**
	 * 设置全局字体
	 * @param fnt
	 */
	private void initGlobalFontSetting(Font fnt){
	    FontUIResource fontRes = new FontUIResource(fnt);
	    for(Enumeration keys = UIManager.getDefaults().keys(); keys.hasMoreElements();){
	        Object key = keys.nextElement();
	        Object value = UIManager.get(key);
	        if(value instanceof FontUIResource) {
				UIManager.put(key, fontRes);
			}
	    }
	}

}
